package com.mengchengnet.chaperonage.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.mengchengnet.chaperonage.BaseActivity;
import com.mengchengnet.chaperonage.R;
import com.mengchengnet.chaperonage.domain.base.JsonBean;
import com.mengchengnet.chaperonage.domain.base.Service;
import com.mengchengnet.chaperonage.util.JsonFileReader;
import com.mengchengnet.chaperonage.util.PreferenceUtil;
import com.mengchengnet.chaperonage.util.Url;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/16.
 */

public class CheckActivity extends BaseActivity implements View.OnClickListener{
    private LinearLayout lin_address;
    private TextView tv_address,tv_skill;
    private EditText ed_name,ed_age,ed_address,ed_skill,ed_self,ed_price;
    private ImageView iv_head,iv_card,iv_health;
    private Button btn_head,btn_card,btn_health,btn_submit;
    private RadioGroup group,type;
    private RequestQueue requestQueue;
    private String sexResult="男";//选择的性别结果
    private String typeResult="1";//陪护类型的性别结果
    private HttpUtils httpUtils;
    private String userId;
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<Service> data=new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    String result = "";
    boolean[] flags;

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    dialogShow();
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check);
        initView();
        initJsonData();

    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
    }

    private void initView() {
        userId=PreferenceUtil.getString(this,"userId");
        toolbarState=TOOLBAR_STYLE_BACK_TITLE;
        initToolbar("上传资料");
        ed_name= (EditText) findViewById(R.id.check_ed_name);
        ed_age= (EditText) findViewById(R.id.check_ed_age);
        ed_address= (EditText) findViewById(R.id.check_ed_address);
        ed_skill= (EditText) findViewById(R.id.check_ed_skill);
        ed_self= (EditText) findViewById(R.id.check_ed_self);
        ed_price= (EditText) findViewById(R.id.check_ed_price);
        iv_head= (ImageView) findViewById(R.id.check_iv_head);
        iv_card= (ImageView) findViewById(R.id.check_iv_card);
        iv_health= (ImageView) findViewById(R.id.check_iv_health);
        btn_head= (Button) findViewById(R.id.check_btn_head);
        btn_card= (Button) findViewById(R.id.check_btn_card);
        btn_health= (Button) findViewById(R.id.check_btn_health);
        btn_submit= (Button) findViewById(R.id.check_btn_submit);
        btn_head.setOnClickListener(this);
        btn_card.setOnClickListener(this);
        btn_health.setOnClickListener(this);
        btn_submit.setOnClickListener(this);
        group= (RadioGroup) findViewById(R.id.check_radioGroup);
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                int id=group.getCheckedRadioButtonId();
                RadioButton button = (RadioButton) findViewById(id);
                sexResult= button.getText().toString();
                Log.e("ooooooooooo", "性别选择结果"+sexResult );
            }
        });
        type= (RadioGroup) findViewById(R.id.check_radioGroupType);
        type.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                int id=type.getCheckedRadioButtonId();
                RadioButton button = (RadioButton) findViewById(id);
                if (button.getText().toString().equals("护理师")){
                    typeResult= "1";
                }else if(button.getText().toString().equals("月嫂")){
                    typeResult= "2";
                }else if(button.getText().toString().equals("催乳师")){
                    typeResult= "3";
                }else {
                    typeResult= "4";
                }

            }
        });
        tv_address= (TextView) findViewById(R.id.check_tv_city);
        lin_address= (LinearLayout) findViewById(R.id.check_lin_address);
        lin_address.setOnClickListener(this);
        tv_skill= (TextView) findViewById(R.id.check_tv_skill);
        tv_skill.setOnClickListener(this);

        requestQueue= Volley.newRequestQueue(getApplication());
        //初始化httpUtils
        httpUtils = new HttpUtils(100000);//设置他连接超时时间是100s
        httpUtils.configCurrentHttpCacheExpiry(5000);//设置缓存有效时间是5s
    }

    private void open(int requestCode){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        intent.putExtra("return-data", false);
        intent.putExtra("crop", "true");
        //设置宽高比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        //设置裁剪图片宽高、
        intent.putExtra("outputX", 450);
        intent.putExtra("outputY", 450);
        if (requestCode==0){
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                    Environment.getExternalStorageDirectory(), "/temp/img0.jpg")));
        }else if(requestCode==1){
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                    Environment.getExternalStorageDirectory(), "/temp/img1.jpg")));
        }else{
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                    Environment.getExternalStorageDirectory(), "/temp/img2.jpg")));
        }
        startActivityForResult(intent,requestCode);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK)
            return;
            //crop(data.getData());
            if(data==null){
                return;//当data为空的时候，不做任何处理
            }
//            Bitmap bitmap1 = null;
//            //获取从相册界面返回的缩略图
//            bitmap1 = data.getParcelableExtra("data");
//            if(bitmap1==null){//如果返回的图片不够大，就不会执行缩略图的代码，因此需要判断是否为null,如果是小图，直接显示原图即可
//                try {
//                    //通过URI得到输入流
//                    InputStream inputStream = this.getContentResolver().openInputStream(data.getData());
//                    //通过输入流得到bitmap对象
//                    bitmap1 = BitmapFactory.decodeStream(inputStream);
//                } catch (FileNotFoundException e) {
//                    e.printStackTrace();
//                }
//            }

            //将选择的图片设置到控件上
        if (requestCode==0){
            Bitmap b= BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()
                    + "/temp/img0.jpg");
            iv_head.setImageBitmap(b);
        }else if(requestCode==1){
            Bitmap b= BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()
                    + "/temp/img1.jpg");
            iv_card.setImageBitmap(b);
        }else if(requestCode==2){
            Bitmap b= BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()
                    + "/temp/img2.jpg");
            iv_health.setImageBitmap(b);
        }


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.check_btn_head:
                open(0);
                //showTakePhotoDialog();
                break;
            case R.id.check_btn_health:
                open(2);
                break;
            case R.id.check_btn_card:
                open(1);
                break;
            case R.id.check_btn_submit:
                check();
                break;
            case R.id.check_lin_address:
                //弹出选择省市的对话框
                showPickerView();
                break;
            case R.id.check_tv_skill:
               if (typeResult.equals("1")){
                   getSkill("1");
               }else if(typeResult.equals("2")){
                   getSkill("2");
               }else if(typeResult.equals("3")){
                   getSkill("3");
               }else if(typeResult.equals("4")){
                   getSkill("4");
               }
                break;
        }

    }

    private void dialogShow(){
        final String [] da=new String[data.size()];
        flags=new boolean[da.length];
        for (int i = 0; i < data.size(); i++) {
            da[i]=data.get(i).getName();
            flags[i]=false;
        }
        result = "";

         new AlertDialog.Builder(this)
                            .setTitle("个人技能")
                            .setMultiChoiceItems(da, null, new DialogInterface.OnMultiChoiceClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which, boolean isChecked) {

                                        flags[which]=isChecked;

                                }
                            })
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    for(int i=0;i<da.length;i++) {
                                        if(flags[i]) {
                                            result=result+da[i]+",";
                                            ed_skill.setText(result);
                                        }
                                    }
                                    Toast.makeText(CheckActivity.this,result, Toast.LENGTH_LONG).show();
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
    }

    private void getSkill(final String type){
        StringRequest request = new StringRequest(Request.Method.POST, Url.getSkill,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Log.e("获取陪护技能信息", "获取陪护技能信息接口返回值："+result );
                        JSONObject jsonObject;
                        try {
                            if(result != null && result.startsWith("\ufeff"))
                            {
                                result =  result.substring(1);
                            }
                            jsonObject = new JSONObject(result);
                            if (jsonObject.getString("code").equals("00")){
                                JSONArray array=jsonObject.getJSONArray("skill_list");
                                Log.e("ppp", "集合长度: "+array.length());
                                data.clear();
                                if (array.length()>0){

                                    for (int i = 0; i < array.length(); i++) {
                                        JSONObject obj = array.getJSONObject(i);
                                        String name = obj.getString("name");
                                        String id = obj.getString("id");
                                        Service s=new Service();
                                        s.setId(id);
                                        s.setName(name);
                                        data.add(s);
                                    }
                                    handler.sendEmptyMessage(0);
                                }else {
                                    handler.sendEmptyMessage(1);
                                }
                            }
                            else {
                                Toast.makeText(CheckActivity.this, "失败", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(CheckActivity.this, "网络异常请稍后重试！", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("version", PreferenceUtil.getString(getApplication(),"versionCode"));
                map.put("cate_id", type);
                return map;
            }
        };
        request.setTag("GetFenZu");
        request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, // 默认超时时间，应设置一个稍微大点儿的
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);

    }

    private void check() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("version", PreferenceUtil.getString(this,"versionCode"));
        Log.e("checkActivity", "version:"+PreferenceUtil.getString(this,"versionCode"));
        Log.e("checkActivity", "userName:"+ed_name.getText().toString());
        Log.e("checkActivity", "sex:"+sexResult);
        Log.e("checkActivity", "careAge:"+ed_age.getText().toString());
        Log.e("checkActivity", "address:"+ed_address.getText().toString());
        Log.e("checkActivity", "skill:"+ed_skill.getText().toString());
        Log.e("checkActivity", "evaluate:"+ed_self.getText().toString());
        Log.e("checkActivity", "price:"+ed_price.getText().toString());
        Log.e("checkActivity", "cityName:"+PreferenceUtil.getString(this,"cityName"));
        Log.e("checkActivity", "city_id:"+PreferenceUtil.getString(this,"cityId"));
        Log.e("checkActivity", "cate_id:"+typeResult);
        params.addBodyParameter("loginId", userId);
        params.addBodyParameter("userName", ed_name.getText().toString());
        params.addBodyParameter("sex", sexResult);
        params.addBodyParameter("careAge", ed_age.getText().toString());
        params.addBodyParameter("address", ed_address.getText().toString());
        params.addBodyParameter("skill", ed_skill.getText().toString());
        params.addBodyParameter("evaluate", ed_self.getText().toString());
        params.addBodyParameter("cate_id", typeResult);
        params.addBodyParameter("cate_id", typeResult);
        params.addBodyParameter("birthday", "1999/03/22");
        params.addBodyParameter("price", ed_price.getText().toString());
        params.addBodyParameter("cityName", PreferenceUtil.getString(this,"cityName"));
        params.addBodyParameter("city_id", PreferenceUtil.getString(this,"cityId"));
        params.addBodyParameter("qualificationCertificate", new File(Environment.getExternalStorageDirectory() +
                "/temp/img0.jpg"));
        params.addBodyParameter("idCard", new File(Environment.getExternalStorageDirectory() +
                "/temp/img1.jpg"));
        params.addBodyParameter("healthCertificate", new File(Environment.getExternalStorageDirectory() +
                "/temp/img2.jpg"));
        upCheck(params, Url.careCheck);


//        RequestParams params2 = new RequestParams();
//        params2.addBodyParameter("version", PreferenceUtil.getString(this,"versionCode"));
//        params2.addBodyParameter("loginId", "156");
//        params2.addBodyParameter("file", new File(Environment.getExternalStorageDirectory()
//                + "/temp/img0.jpg"));
//        upLoadImage(params2, Url.uploadImage);


    }


    /**
     * 图片上传
     * @param paramss
     * @param
     * @param url 服务器地址
     */
    public void upLoadImage(RequestParams paramss,  String url){

        httpUtils.send(HttpRequest.HttpMethod.POST, url, paramss, new RequestCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                super.onLoading(total, current, isUploading);
            }

            @Override
            public void onSuccess(ResponseInfo<Object> responseInfo) {
                Log.e("checkActivity", "onSuccess: "+responseInfo.result.toString());
                Toast.makeText(getApplicationContext(), "图片上传成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }

        });
    }


    public void upCheck(RequestParams paramss,  String url){

        final HttpHandler<Object> send = httpUtils.send(HttpRequest.HttpMethod.POST, url, paramss, new RequestCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                super.onLoading(total, current, isUploading);
            }

            @Override
            public void onSuccess(ResponseInfo<Object> responseInfo) {
                Log.e("checkActivity", "onSuccess: " + responseInfo.result.toString());
                try {
                    JSONObject json = new JSONObject(responseInfo.result.toString());
                    if ((json.getString("code").equals("00"))){
                        Toast.makeText(CheckActivity.this, "上传审核信息成功", Toast.LENGTH_SHORT).show();
                        startActivityAndFinish(CareMainActivity.class);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {

            }

        });
    }

    public void showPickerView() {
        OptionsPickerView pvOptions=new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String text = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);
                Toast.makeText(CheckActivity.this, text, Toast.LENGTH_SHORT).show();
                tv_address.setText(text);
            }
        }).setTitleText("")
                .setDividerColor(Color.GRAY)
                .setTextColorCenter(Color.GRAY)
                .setContentTextSize(13)
                .setOutSideCancelable(false)
                .build();
          /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {   //解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        //  获取json数据
        String JsonData = JsonFileReader.getJson(this, "province_data.json");
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }
}
